// 顺序请求,全部完成后返回最后请求结果,中间有失败则停止继续请求,直接返回失败的结果
// 127.0.0.1:3000/proxy/queue/s?query=[{"path":"serveruser\/user\/User\/login","param":{"phone":"13181262939","login_password":"12345678","token":"b49baca86cf59b174feae087a63d8656"}}]
// 127.0.0.1:3000/proxy/queue/s?query=[{"path":"serveruser\/user\/User\/list","param":{"page":"1","list_rows":"15"}}]
// 127.0.0.1:3000/proxy/queue/s?query=[{"path":"serveruser\/user\/User\/list","param":{"page":"1","list_rows":"15"}},{"path":"serveruser\/user\/User\/info","param":{"id":"1"}}]&success=1,0

// post方式  127.0.0.1:3000/proxy/queue
// {"query":[{"path":"serveruser/user/User/list","param":{"page":"1","list_rows":"15"}},{"path":"serveruser/user/User/info","param":{"id":"1"}}],"success":"1,0"}

const express = require('express')
const router = express.Router()
const http = require('http')

router.get('/', function (sreq, sres, next){
  console.log('get return')
  sres.json({status: -5, code: 404, msg: 'upload只能用post方式传参', res: {}})
})

router.post('/', function (sreq, sres, next) {
  sres.setHeader('Access-Control-Allow-Origin', '*');
  console.log('转发请求')
  var opts={
    host: 'http://www.newthink.local/', // 跨域访问的主机ip  
    port: 80,
    path: 'manage/index/upload',
    headers: sreq.headers,
    method: 'POST'
  };
  var content = ''

  sreq.on("data",function(data){//接收参数 ------ sreq.on("data",function(data){});接收html中ajax传递的参数  
    var req = http.request(opts, function(res) {
      res.on('data', function (body) {
        console.log('return')
        content += body
      }).on('end', function () {
        // 返回给前台
        if(res.headers != null && res.headers['set-cookie'] != null){
          console.log("=======res.headers.cookie======="+res.headers.cookie);
          sres.writeHead(200, {
            'Content-Type': 'text/html',
            'Set-Cookie': res.headers['set-cookie']
          }) // 将cookie放到response中  
        } else {
          sres.writeHead(200, {
            'Content-Type': 'text/html',
            'aaa': 'bbb'
          })
        }

        sres.write(content)
        sres.end()
      })
    }).on('error', function(e) {
      console.log("Got error: " + e.message)
    })
    // console.log("固定参数===="+post_data);
    // console.log("接收参数===="+data+"\n");
    if(sreq.headers.cookie != null){  
       req.setHeader('Cookie',sreq.headers.cookie)
    } //获取request中的cookie</span>

    req.write(data+"\n")
    req.end()
  })
})

module.exports = router
